import { Component, ViewChild} from '@angular/core';
import { NavController, ToastController, Slides, LoadingController, AlertController, Content} from 'ionic-angular';

//massage
import { MassagePage } from '../massage/massage';
//确认订单
import { ConfirmOrderPage } from '../confirm-order/confirm-order';

// import { RegisterPage } from '../register/register';
import { LoginPage } from '../login/login';

//商品详情
import { GoodsInfoPage } from '../goods-info/goods-info';
//点击首页轮播
import { HomeBannerPage} from '../home-banner/home-banner'
import { KataotaoPage} from '../kataotao/kataotao'
import { Https } from '../../app/http.service'
@Component({
	selector: 'page-home',
	templateUrl: 'home.html',
})

export class HomePage {
	@ViewChild(Slides) homeslides: Slides;
	@ViewChild(Content) content: Content;
	Url: string = new Https().Url + "act=goods&op=home_goods"
	petArray = ['kittens', 'unicom', 'telcom', 'puppies'];
	arr = ['mobiles', 'unicoms', 'telcoms', 'jds'];
	pet: string = this.petArray[0];
	items = [];
	card = [];
	data = 0;
	banner = ["","",""];
	userPic:string;
	currentIndex:number
	constructor(public navCtrl: NavController, public toastCtrl: ToastController, public loadingCtrl: LoadingController, public alertCtrl: AlertController) {
		this.currentIndex = 0
		this.loadData(0,0);
	} 
	
	loadData(status:number,page:number){
		fetch(this.Url + "&status=" + status + "&page=" + page, {
			method: "get",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
		}).then((data) => {

			data.text().then((json) => {
				if (json != '') {
					if (status == 0 && page == 0) {
						this.card = [];						
					}
					let resource = JSON.parse(json).datas;
					if (page == 0){
						this.banner = resource.banner						
					}else{
						this.items['refresh'] = resource
					}
					console.log(this.items)
					if (this.card['mobiles'] == null){
						this.card['mobiles'] = resource.mobile
						this.items['mobiles'] = resource.mobile == undefined ? 0 : 1;	
					} else if (resource.mobile != undefined){
						if (resource.mobile != null) {
							for (let item of resource.mobile){
								this.card['mobiles'].push(item);
							}
						}
					}
					if (this.card['unicoms'] == null) {
						this.card['unicoms'] = resource.unicom
						this.items['unicoms'] = resource.unicom == undefined ? 0 : 1;
					} else if (resource.unicom != undefined) {
						if (resource.unicom != null){
							for (let item of resource.unicom) {
								this.card['unicoms'].push(item);
							}
						}
						
					}
					if (this.card['telcoms'] == null) {
						this.card['telcoms'] = resource.telcom
						this.items['telcoms'] = resource.telcom == undefined ? 0 : 1;
					} else if (resource.telcom != undefined) {
						if (resource.telcoms != null) {
							for (let item of resource.telcom) {
								this.card['telcoms'].push(item);
							}
						}
						
					}
					if (this.card['jds'] == null) {
						this.card['jds'] = resource.jd
						this.items['jds'] = resource.jd == undefined ? 0 : 1;
					} else if (resource.jds!= undefined) {
						if (resource.jd != null) {
							for (let item of resource.jd) {
								this.card['jds'].push(item);
							}
						}
						
					}
					// this.card['jds'] = resource.jd
					// this.items['jds'] = resource.jd == undefined ? 0 : 1;
					// this.card['unicoms'] = resource.unicom
					// this.items['unicoms'] = resource.unicom == undefined ? 0 : 1;
					// this.card['telcoms'] = resource.telcom
					// this.items['telcoms'] = resource.telcom == undefined ? 0 : 1;
					// console.log(this.card);
				} else {
					this.items['mobiles'] = 0;
					this.items['jds'] = 0;
					this.items['unicoms'] = 0;
					this.items['telcoms'] = 0;
					// let alert = this.alertCtrl.create({
					// 	title: '温馨提示',
					// 	subTitle: '网络连接错误',
					// 	buttons: ['好']
					// });
					// alert.present();
				}
			})


		}).catch((err) => {
			this.items['mobiles'] = 0;
			this.items['jds'] = 0;
			this.items['unicoms'] = 0;
			this.items['telcoms'] = 0;
			// let alert = this.alertCtrl.create({
			// 	title: '温馨提示',
			// 	subTitle: "网络连接错误",
			// 	buttons: ['好']
			// });
			// alert.present();
		})
	}

	doInfinite(infiniteScroll,typeId) {
		let len = this.card[this.arr[typeId]].length;
		console.log('开始请求数据');
		this.loadData(typeId, len);
		
		setTimeout(() => {
			infiniteScroll.complete();
		}, 2000);
	} 

	//抢购
	openBuy(num, price, id, img, buyname, goodsName, zhuanmai_rate){
		// let toast = this.toastCtrl.create({
		// 	message: '抢购正在抢救中',
		// 	duration: 3000
		// });   
		// toast.present();
		console.log(id)
		if(localStorage.getItem("loginState") == '0'){
			let loader = this.loadingCtrl.create({
				content: "请稍等...",
			});
			loader.present();
			setTimeout(() => {
				this.navCtrl.push(ConfirmOrderPage, {
					"num": num,
					"price": price,
					"id": id,
					"img": img,
					"buyname": buyname,
					"goodsname": goodsName,
					"zhuanmai_rate":zhuanmai_rate,
				})
			}, 1500);

			setTimeout(() => {
				loader.dismiss();
			}, 3000);
		}else{
			// let alert = this.alertCtrl.create({
			// 	title: '温馨提示',
			// 	subTitle: "请先登录！",
			// 	buttons: ['OK']
			// });
			// alert.present();
			this.navCtrl.push(LoginPage);
		}
		
	}

	openMassage(){
		this.navCtrl.push(MassagePage) 
	}

	ionViewDidEnter($event) {
		
		if (localStorage.getItem("userPic") != null) {
			this.userPic = localStorage.getItem("userPic")
		} else {
			this.userPic = './assets/imgs/user.png';
		}
	}

	doRefresh(refresher){
		// console.log(refresher) 
		this.loadData(this.currentIndex, 0)
		setTimeout(()=>{
			refresher.complete()			
		},2000)
	}

	/* 
	 slide改变index触发
   */
	slideChanged($event) {
			
		//获取当前页面index
		let currentIndex = this.homeslides.getActiveIndex();
		// this.loadData(currentIndex, 0);	
		// console.log(111112)
		this.currentIndex = currentIndex;
		if (this.card[this.arr[currentIndex]] == null){
			this.loadData(currentIndex, 0);
		}
		if (currentIndex > (this.homeslides.length() - 1)){
			currentIndex = this.homeslides.length() - 1;
		}
		//定位segment
		this.pet = this.petArray[currentIndex];
		//获取slide子元素
		let brother = $event.container.children[0].children;
		
		for (let i = 0; i < brother.length;i++){
			if (i != currentIndex){ 
				if (brother[i].children[0].children[0].offsetHeight > brother[currentIndex].children[0].children[0].offsetHeight){
					brother[i].children[0].children[0].style = "height:" + brother[currentIndex].children[0].children[0].offsetHeight + "px"
				}
			}else{
				brother[i].children[0].children[0].style = "height:unset"
			}
			
		}
		//回到顶部
		// this.content.scrollTo(0, 180, 0); 
	}
    /* 
      点击tab定位
    */
	swipeEvnet(event) {
		//跳转到指定页面
		//获取ID定位
		this.homeslides.slideTo(this.petArray.indexOf(event.target.id));
		console.log(this.petArray.indexOf(event.target.id))
	}
	//商品详情
	goodsDetail(num, price, id, img, buyname, goodsName, quanjia, huanmai_rate, goods_info_type){

		this.navCtrl.push(GoodsInfoPage, {
			"num": num,
			"price": price,
			"id": id,
			"img": img,
			"buyname": buyname, 
			"goodsname": goodsName,
			"quanjia": quanjia,
			"huanmai_rate": huanmai_rate,
			"goods_info_type": goods_info_type
		})
	}
	bannerClick(index){
		switch (index) {
			case 1:
				console.log(1)
				this.navCtrl.push(HomeBannerPage,{"banner_id":index})
				break;
			case 2:
				console.log(2)
				this.navCtrl.push(HomeBannerPage, { "banner_id": index })		
				break;
			case 3:
				console.log(3)
				this.navCtrl.push(KataotaoPage)
				break;
		}
	}
}
